#include "RemoteWindowsMedia.h"
#include "WMPRemoteHost.h"

#include "wmp.h"

CComModule _Module;

RemoteWindowsMedia::RemoteWindowsMedia()
{
	m_pView = NULL;

	CreateWmpOcx();
}

RemoteWindowsMedia::~RemoteWindowsMedia()
{
    m_spPlayer = NULL;

    if(m_pView != NULL)
    {
        delete m_pView;
        m_pView = NULL;
    }
}

LRESULT RemoteWindowsMedia::Pause()
{
    if(m_spPlayer != NULL)
    {
		CComPtr<IWMPControls> m_control;
		WMPPlayState m_playstate;
		
		this->m_spPlayer->get_controls(&m_control);

		this->m_spPlayer->get_playState(&m_playstate);

		if(m_playstate == wmppsStopped || m_playstate == wmppsPaused)
			m_control->play();
		
		else
			m_control->pause();
    }

	return 0;
}

HRESULT RemoteWindowsMedia::CreateWmpOcx()
{
    CComPtr<IAxWinHostWindow>           spHost;
    RECT                                rect = {0, 0, 0, 0};
    HRESULT                             hr = E_FAIL;
    CComPtr<IObjectWithSite>            spHostObject;
    CComObject<WMPRemoteHost>          *pRemoteHost = NULL;
    IUnknown                            *punkSite = NULL;

    m_pView = new CAxWindow();
    hr = m_pView ? S_OK : AtlHresultFromLastError();
    
    if(SUCCEEDED(hr) && m_pView)
    {
		m_pView->Create(NULL, rect, NULL, WS_VISIBLE);
        if(::IsWindow(m_pView->m_hWnd))
        {
            hr = m_pView->QueryHost(IID_IObjectWithSite, (void **)&spHostObject);
        }
        
        if(SUCCEEDED(hr) && spHostObject.p)
        {
            hr = CComObject<WMPRemoteHost>::CreateInstance(&pRemoteHost);
            if(pRemoteHost)
            {
                hr = ((IUnknown *)(IWMPRemoteMediaServices *)pRemoteHost)->QueryInterface(IID_IUnknown, (void **)&punkSite);
            }
        }
        
        if(SUCCEEDED(hr) && punkSite)
        {
            hr = spHostObject->SetSite(punkSite);
            punkSite->Release();
            punkSite = NULL;
        }
        
        if(SUCCEEDED(hr))
        {
            hr = m_pView->QueryHost(&spHost);
        }
        
        if(SUCCEEDED(hr) && spHost.p)
        {
            hr = spHost->CreateControl(L"{6BF52A52-394A-11d3-B153-00C04F79FAA6}", m_pView->m_hWnd, 0);
        }

        if(SUCCEEDED(hr))
        {
            hr = m_pView->QueryControl(&m_spPlayer);
        }
    }
    
    return hr;
}